import { useState, useRef, useCallback } from 'react'
import { Button } from '@/components/ui/button'
import { X, Check, MapPin } from 'lucide-react'

interface RegionSelectorProps {
  imageUrl: string
  onConfirm: (region: { x: number; y: number; width: number; height: number }) => void
  onCancel: () => void
}

export function RegionSelector({ imageUrl, onConfirm, onCancel }: RegionSelectorProps) {
  const [selection, setSelection] = useState<{
    startX: number
    startY: number
    currentX: number
    currentY: number
  } | null>(null)
  
  const [isDragging, setIsDragging] = useState(false)
  const imageRef = useRef<HTMLImageElement>(null)

  const handleMouseDown = useCallback((e: React.MouseEvent<HTMLDivElement>) => {
    if (!imageRef.current) return
    
    const rect = imageRef.current.getBoundingClientRect()
    const x = e.clientX - rect.left
    const y = e.clientY - rect.top
    
    setSelection({
      startX: x,
      startY: y,
      currentX: x,
      currentY: y,
    })
    setIsDragging(true)
  }, [])

  const handleMouseMove = useCallback((e: React.MouseEvent<HTMLDivElement>) => {
    if (!isDragging || !selection || !imageRef.current) return
    
    const rect = imageRef.current.getBoundingClientRect()
    const x = Math.max(0, Math.min(e.clientX - rect.left, rect.width))
    const y = Math.max(0, Math.min(e.clientY - rect.top, rect.height))
    
    setSelection(prev => prev ? { ...prev, currentX: x, currentY: y } : null)
  }, [isDragging, selection])

  const handleMouseUp = useCallback(() => {
    setIsDragging(false)
  }, [])

  const handleConfirm = () => {
    if (!selection || !imageRef.current) return
    
    const rect = imageRef.current.getBoundingClientRect()
    const img = imageRef.current
    
    // 计算选择区域相对于原始图片的坐标
    const scaleX = img.naturalWidth / rect.width
    const scaleY = img.naturalHeight / rect.height
    
    const x = Math.min(selection.startX, selection.currentX) * scaleX
    const y = Math.min(selection.startY, selection.currentY) * scaleY
    const width = Math.abs(selection.currentX - selection.startX) * scaleX
    const height = Math.abs(selection.currentY - selection.startY) * scaleY
    
    if (width < 10 || height < 10) {
      alert('选择区域太小，请重新选择')
      return
    }
    
    const region = {
      x: Math.round(x),
      y: Math.round(y),
      width: Math.round(width),
      height: Math.round(height),
    }
    
    // 确认选择，自动关闭组件
    onConfirm(region)
  }

  // 获取当前选择的实际坐标信息（用于显示）
  const getActualRegion = () => {
    if (!selection || !imageRef.current) return null
    
    const rect = imageRef.current.getBoundingClientRect()
    const img = imageRef.current
    
    // 计算选择区域相对于原始图片的坐标
    const scaleX = img.naturalWidth / rect.width
    const scaleY = img.naturalHeight / rect.height
    
    const x = Math.min(selection.startX, selection.currentX) * scaleX
    const y = Math.min(selection.startY, selection.currentY) * scaleY
    const width = Math.abs(selection.currentX - selection.startX) * scaleX
    const height = Math.abs(selection.currentY - selection.startY) * scaleY
    
    return {
      x: Math.round(x),
      y: Math.round(y),
      width: Math.round(width),
      height: Math.round(height),
    }
  }

  const getSelectionStyle = () => {
    if (!selection) return {}
    
    const left = Math.min(selection.startX, selection.currentX)
    const top = Math.min(selection.startY, selection.currentY)
    const width = Math.abs(selection.currentX - selection.startX)
    const height = Math.abs(selection.currentY - selection.startY)
    
    return {
      left: `${left}px`,
      top: `${top}px`,
      width: `${width}px`,
      height: `${height}px`,
    }
  }

  return (
    <div className="fixed inset-0 z-50 bg-black/90 flex flex-col">
      {/* 顶部工具栏 */}
      <div className="bg-background border-b p-4 flex items-center justify-between">
        <div className="flex-1">
          <h3 className="text-lg font-semibold">选择监控区域</h3>
          <p className="text-sm text-muted-foreground">
            拖拽鼠标选择需要监控的屏幕区域
          </p>
          {/* 显示当前选择的坐标信息 */}
          {selection && (() => {
            const actualRegion = getActualRegion()
            return actualRegion && (
              <div className="mt-2 flex items-center gap-4 text-sm">
                <div className="flex items-center gap-1 text-blue-600 dark:text-blue-400">
                  <MapPin className="h-4 w-4" />
                  <span>坐标: ({actualRegion.x}, {actualRegion.y})</span>
                </div>
                <div className="text-green-600 dark:text-green-400">
                  <span>尺寸: {actualRegion.width} × {actualRegion.height}</span>
                </div>
              </div>
            )
          })()}
        </div>
        <div className="flex gap-2 ml-4">
          <Button onClick={onCancel} variant="outline">
            <X className="mr-2 h-4 w-4" />
            取消
          </Button>
          <Button 
            onClick={handleConfirm} 
            disabled={!selection}
            className="min-w-24"
          >
            <Check className="mr-2 h-4 w-4" />
            确认选择
          </Button>
        </div>
      </div>

      {/* 图片选择区域 */}
      <div className="flex-1 flex items-center justify-center p-4 overflow-auto">
        <div 
          className="relative cursor-crosshair"
          onMouseDown={handleMouseDown}
          onMouseMove={handleMouseMove}
          onMouseUp={handleMouseUp}
          onMouseLeave={handleMouseUp}
        >
          <img 
            ref={imageRef}
            src={imageUrl} 
            alt="屏幕截图" 
            className="max-w-full max-h-[calc(100vh-200px)] select-none"
            draggable={false}
          />
          
          {/* 选择框 */}
          {selection && (
            <div 
              className="absolute border-2 border-blue-500 bg-blue-500/20"
              style={getSelectionStyle()}
            >
              {(() => {
                const actualRegion = getActualRegion()
                return actualRegion && (
                  <div className="absolute -top-12 left-0 bg-blue-500 text-white text-xs px-3 py-2 rounded-lg shadow-lg">
                    <div className="font-semibold mb-1">
                      {actualRegion.width} × {actualRegion.height}
                    </div>
                    <div className="opacity-90">
                      坐标: ({actualRegion.x}, {actualRegion.y})
                    </div>
                  </div>
                )
              })()}
            </div>
          )}
        </div>
      </div>

      {/* 底部提示 */}
      <div className="bg-muted border-t p-3 text-center text-sm text-muted-foreground">
        💡 提示: 选择包含验证弹窗可能出现的区域，区域越小性能越好
      </div>
    </div>
  )
}

